package com.shine.minepressure.ui.history;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shine.minepressure.BR;
import com.shine.minepressure.R;
import com.shine.minepressure.app.Constants;
import com.shine.minepressure.base.BaseFragment;
import com.shine.minepressure.bean.StationHisFaultBean;
import com.shine.minepressure.bean.StationMessageBean;
import com.shine.minepressure.databinding.FragmentHistoryChild2Binding;
import com.shine.minepressure.http.ApiException;
import com.shine.minepressure.http.ECObserver;
import com.shine.minepressure.http.RetrofitClient;
import com.shine.minepressure.http.RxUtils;
import com.shine.minepressure.http.Service;
import com.shine.minepressure.ui.adapter.HistoryDataFragment2Adapter;
import com.shine.minepressure.ui.history.viewModel.HistoryDataChildViewModel;
import com.shine.minepressure.utils.DateUtils;
import com.shine.minepressure.view.pop.HistoryDataPopup;

import java.util.ArrayList;
import java.util.List;

public class HistoryDataChild2Fragment extends BaseFragment<FragmentHistoryChild2Binding, HistoryDataChildViewModel> {
    private HistoryDataFragment2Adapter historyDataFragment2Adapter;
    private HistoryDataPopup historyDataPopup;
    private int page = 1;
    private int mStationPosition;
    private String mStationName = "全部";
    private String mStationId = "-1";
    private static List<StationMessageBean.RowsDTO> mStationMessageList = new ArrayList<>();
    private static List<String> mStationMessage = new ArrayList<>();

    private String mInstallPosition;
    private String mBeginTime = DateUtils.getCurrDate(DateUtils.LONG_DATE + " 00:00:00");
    private String mEndTime = DateUtils.getCurrDate(DateUtils.LONG_DATE + " 23:59:59");

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_history_child2;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public HistoryDataChildViewModel initViewModel() {
        return new HistoryDataChildViewModel(getActivity());
    }

    @Override
    public void initData() {
        super.initData();

        historyDataFragment2Adapter = new HistoryDataFragment2Adapter(binding.recyclerView);
        binding.recyclerView.setAdapter(historyDataFragment2Adapter);

        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.refreshLayout.finishRefresh(1000);
                binding.refreshLayout.setEnableLoadMore(true);
                historyDataFragment2Adapter.clear();
                page = 1;
                getStationHisFault();
            }
        });
//        binding.refreshLayout.setEnableLoadMore(false);
        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                binding.refreshLayout.finishLoadMore(1000);
                page++;
                getStationHisFault();
            }
        });

        binding.search.setOnClickListener(this);

        getStationHisFault();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search:
                search();
                break;
        }
    }

    public static void setStationMessage(List<StationMessageBean.RowsDTO> areaStationList, List<String> stationMessage) {
        mStationMessageList.clear();
        mStationMessage.clear();
        mStationMessageList.addAll(areaStationList);
        mStationMessage.add("全部");
        mStationMessage.addAll(stationMessage);
    }

    /**
     * 分站信息
     */
    private void getStationMessage() {
//        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .getStationMessage()
                .compose(RxUtils.bindToLifecycle(this))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .subscribe(new ECObserver<StationMessageBean>() {
                    @Override
                    protected void _onNext(StationMessageBean stationMessageBean) {
//                        dismissLoading();
                        if (stationMessageBean.getTotal().equals("0"))
                            return;
                        List<String> stationMessage = new ArrayList<>();
                        for (StationMessageBean.RowsDTO rowsDTO : stationMessageBean.getRows()) {
                            stationMessage.add(rowsDTO.getStationName());
                        }
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }

    /**
     * 历史分站故障
     */
    private void getStationHisFault() {
        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .getStationHisFault(mStationId, mBeginTime, mEndTime, Constants.PAGE_SIZE + "", page + "")
                .compose(RxUtils.bindToLifecycle(this))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .subscribe(new ECObserver<StationHisFaultBean>() {
                    @Override
                    protected void _onNext(StationHisFaultBean stationHisFaultBean) {
                        dismissLoading();

                        binding.totalNum.setText(stationHisFaultBean.getTotal() + "");
                        historyDataFragment2Adapter.addMoreData(stationHisFaultBean.getRows());
                        if (stationHisFaultBean.getRows().size() < Constants.PAGE_SIZE) {
                            binding.refreshLayout.setEnableLoadMore(false);
                        }
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }


    private void search() {
        historyDataPopup = new HistoryDataPopup(2, getActivity(), mStationMessage, mStationName,
                mBeginTime, mEndTime, mStationPosition);
        new XPopup.Builder(getActivity())
                .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                .enableDrag(true)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .isThreeDrag(true) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                .setPopupCallback(new SimpleCallback() {
                    @Override
                    public void onShow(BasePopupView popupView) {
                    }

                    @Override
                    public void onDismiss(BasePopupView popupView) {
                    }
                })
                .asCustom(historyDataPopup)/*.enableDrag(false)*/
                .show();
        historyDataPopup.show();
        historyDataPopup.setListener(new OnConfirmListener() {
            @Override
            public void onConfirm() {
            }
        }, new OnCancelListener() {
            @Override
            public void onCancel() {
            }
        }, new HistoryDataPopup.OnPopClickListener() {

            @Override
            public void onConfirmClick(Integer stationPosition, String stationName, String timeStart, String timeEnd) {
                mStationPosition = stationPosition;
                mStationName = stationName;
                mBeginTime = timeStart;
                mEndTime = timeEnd;
                if (stationPosition == 0)
                    mStationId = "-1";
                else
                    mStationId = mStationMessageList.get(stationPosition - 1).getStationID();

                binding.refreshLayout.setEnableLoadMore(true);
                historyDataFragment2Adapter.clear();
                page = 1;
                getStationHisFault();
            }
        });
    }
}